package com.hzgj.bcl.soa.rpc.retry;

import com.hzgj.bcl.soa.util.CondVar;
import com.hzgj.bcl.soa.util.Condition;

import java.net.InetAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import io.netty.channel.Channel;

public class ConnectionState extends RetryPolicy.InvokeState implements Condition {

    protected final Lock lock = new ReentrantLock();
    protected final CondVar cond = new CondVar(lock);
    public InetAddress address;
    public int port;
    private Channel channel;
    private volatile AtomicBoolean cancel = new AtomicBoolean(false);

    public ConnectionState(InetAddress address, int port) {
        this.port = port;
        this.address = address;
    }

    public ConnectionState(Channel channel) {
        this.channel = channel;
    }

    public Channel getChannel() {
        if (retryCount > 0) {
            cond.waitFor(this);
        }
        return channel;
    }

    public void setChannel(Channel channel) {
        cond.signal(true);
        this.channel = channel;
    }

    @Override
    public boolean isMet() {
        return channel != null || cancel.get();
    }

    public void cancel() {
        cancel.set(true);
        cond.signal(true);
    }

    /**
     * 获取此链接的地址格式为 host:port
     *
     * @return
     */
    public String url() {
        return String.format("%s:%s", address, port);
    }
}